package com.efast.cafe.portal.service.common.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.efast.cafe.commponent.crud.service.impl.CrudSqlGenerateUtils;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.jdbc.JdbcDao;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.cafe.portal.bean.common.AttachmentFormBean;
import com.efast.cafe.portal.bean.common.EntityFieldDetailBean;
import com.efast.cafe.portal.bean.common.EntityFieldInfoBean;
import com.efast.cafe.portal.bean.common.EntityInfoBean;
import com.efast.cafe.portal.bean.common.tree.PortalTreeBean;
import com.efast.cafe.portal.bean.common.tree.PortalTreeMoveBean;
import com.efast.cafe.portal.bean.common.tree.TreeNodeBean;
import com.efast.cafe.portal.dao.common.PortalTreeDao;
import com.efast.cafe.portal.entity.common.tree.*;
import com.efast.cafe.portal.service.common.*;
import com.efast.cafe.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * <p>
 * Service接口实现类
 * </p>
 * <p>
 * Table: portal_tree -
 * </p>
 *
 * @since 2018-04-25 11:04:19
 */
@Service
@Transactional
public class PortalTreeServiceImpl implements IPortalTreeService {

	private PortalTreeDao portalTreeDao;
	@Autowired
	private IPortalTreeTypeService portalTreeTypeService;

	@Autowired
	private IEntityInfoQueryService entityInfoQueryService;
	@Autowired
	private CrudSqlGenerateUtils crudSqlGenerateUtils;
	@Autowired
	@Qualifier("jdbcDao")
	private JdbcDao jdbcDao;
	@Autowired
	private IPortalTreeNodeRefService portalTreeNodeRefService;

	@Autowired
	private IPortalAttachmentService portalAttachmentService;

	@Autowired
	private IPortalTreeService portalTreeService;

	@Autowired
	public void setPortalTreeDao(PortalTreeDao portalTreeDao) {
		this.portalTreeDao = portalTreeDao;
	}

	public PortalTree selectByPrimaryKey(Integer id) {
		return portalTreeDao.selectByPrimaryKey(id);
	}

	public void deleteByPrimaryKey(Integer id) {
		portalTreeDao.deleteByPrimaryKey(id);
	}

	public Integer insert(PortalTree obj) {
		return portalTreeDao.insert(obj);
	}

	public void updateByPrimaryKeySelective(PortalTree obj) {
		portalTreeDao.updateByPrimaryKeySelective(obj);
	}

	public void updateByPrimaryKey(PortalTree obj) {
		portalTreeDao.updateByPrimaryKey(obj);
	}

	@Override
	public Map<String, Object> queryTreeByCodeAndRootEntityKey(PortalTreeBean obj) {
		// TODO Auto-generated method stub
		CommonTree commonTree = new CommonTree();
		Map<String, Object> maps = new HashMap<>();
		PortalTreeType portalTreeType = portalTreeTypeService.selectByTreeByCodeAndRootEntityKey(obj.getTreeTypeCode(),
				obj.getRootEntityKey());
		maps.put("treeStructure", portalTreeType.getTreeStructure());
		JSONObject jsonObject = (JSONObject) JSONObject.parseObject(portalTreeType.getTreeStructure()).get("display");
		boolean asyncTreeLoad = jsonObject.getBooleanValue("asyncTreeLoad");
		Map<String, String> mapParentKey = new HashMap<>();
		List<JSONObject> treeNodeBeans = (List<JSONObject>) JSONObject
				.parseObject(portalTreeType.getTreeStructure()).get("Nodes");
		for (JSONObject treeNodeBean2 : treeNodeBeans) {
			TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
			// if(treeNodeBean.getTreeLevel()== (num+1)){
			JSONArray jsonArrays = treeNodeBean2.getJSONArray("childs");
			if (jsonArrays.size() > 0) {
				for (int i = 0; i < jsonArrays.size(); i++) {
					JSONObject job = jsonArrays.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
					String entityKey = job.getString("entityKey");
					if(mapParentKey.containsKey(entityKey)){
						mapParentKey.put(entityKey,mapParentKey.get(entityKey)+"-"+treeNodeBean.getEntityKey());
					}else{
						mapParentKey.put(entityKey,treeNodeBean.getEntityKey());
					}
				}
			}
		}
		if (portalTreeType.getStoreType() == 1) {

			Map<String, Integer> map = new HashMap<>();
			EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(obj.getRootEntityKey());
			List<Object> params = new ArrayList<>();
			String sql = crudSqlGenerateUtils.buildFindSql(entityInfo.getTableName(), map, entityInfo.getAttrs(),
					entityInfo.getExtAttrs(), false, params);
			List<Map<String, Object>> data = new ArrayList<>();

			for (JSONObject treeNodeBean2 : treeNodeBeans) {
				TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
				entityInfo = entityInfoQueryService.queryEntityInfo(treeNodeBean.getEntityKey());
				// 获取实体定义
				if (null == entityInfo) {
					throw new ServiceException("crud.error.entity.definition", obj.getRootEntityKey());
				}
				params = new ArrayList<>();
				sql = this.buildFindSql(entityInfo.getTableName(), map, entityInfo.getAttrs(), entityInfo.getExtAttrs(),
						false, params);
				List<Map<String, Object>> datas = jdbcDao.queryForListMap(sql, params);
				List<Map<String, Object>> datas1 = new ArrayList<>();
				for (Map<String, Object> map2 : datas) {
					// if(map2.get("parentId")!=null){
					map2.put("entityKey", treeNodeBean.getEntityKey());
					map2.put("treeLevel", treeNodeBean.getTreeLevel());
					map2.put("entityName", entityInfo.getEntityName());
                    String parentKey = mapParentKey.get(treeNodeBean.getEntityKey())!=null && mapParentKey.get(treeNodeBean.getEntityKey()).indexOf("-")>=0 ? (mapParentKey.get(treeNodeBean.getEntityKey()).split("-")[0]+String.valueOf(map2.get("parentId")) +"-"+ mapParentKey.get(treeNodeBean.getEntityKey()).split("-")[1]+String.valueOf(map2.get("parentId")) ) :(mapParentKey.get(treeNodeBean.getEntityKey())+String.valueOf(map2.get("parentId"))) ;
                    map2.put("parentKey",treeNodeBean.getTreeLevel()!=0? parentKey:null);
					map2.put("idKey", treeNodeBean.getEntityKey()+String.valueOf(map2.get("id")));
					datas1.add(map2);
					// }
				}
				data.addAll(datas1);
			}
			List<TreeNode> nodes = new ArrayList<>();
			List<String> dataMap = new ArrayList<>();
			List<TreeNode> nodesQuery = new ArrayList<>();
			List<TreeNode> nodesQuery2 = new ArrayList<>();
			List<Integer> dataMapQuery = new ArrayList<>();
			List<Map<String, Object>> dataQuery = new ArrayList<>();
			dataMap = getChildById(dataMap, data, obj.getRootEntityKey()+obj.getId());
			for (Map<String, Object> map2 : data) {
				if (dataMap.contains((String) map2.get("entityKey")+(Integer) map2.get("id"))) {
					TreeNode treeNode = commonTree.transform(map2);
					nodes.add(treeNode);
					TreeNode treeNode1 = commonTree.transform(map2);
					if (!StringUtil.isNullOrBlank(obj.getNodeName()) && !StringUtil.isNullOrBlank(obj.getNodeType())) {
						if (obj.getNodeType().indexOf((String) map2.get("entityKey")) >= 0) {
							for (JSONObject treeNodeBean2 : treeNodeBeans) {
								TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
								String displayName = treeNodeBean2.getJSONObject("display").getString("displayName");
								if (treeNodeBean.getEntityKey().equals((String) map2.get("entityKey"))) {
									if (((String) map2.get(displayName))
											.indexOf(obj.getNodeName()) >= 0) {
										if (!dataMapQuery.contains((Integer) map2.get("id"))) {
											dataMapQuery.add((Integer) map2.get("id"));
											dataQuery.add(map2);
											// nodesQuery2.add(treeNode1);
											getParentById(dataQuery, nodesQuery2, data, (Integer) map2.get("parentId"),
													dataMapQuery, obj.getNodeType());
										}
									}
								}

							}
						}

					} else if (!StringUtil.isNullOrBlank(obj.getNodeName())) {
						for (JSONObject treeNodeBean2 : treeNodeBeans) {
							TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
							String displayName = treeNodeBean2.getJSONObject("display").getString("displayName");
							if (treeNodeBean.getEntityKey().equals((String) map2.get("entityKey"))) {
								if (((String) map2.get(displayName))
										.indexOf(obj.getNodeName()) >= 0) {
									if (!dataMapQuery.contains((Integer) map2.get("id"))) {
										dataMapQuery.add((Integer) map2.get("id"));
										dataQuery.add(map2);
										nodesQuery.add(treeNode1);
										getParentById(dataQuery, nodesQuery, data, (Integer) map2.get("parentId"),
												dataMapQuery);
									}
								}
							}

						}
					} else if (!StringUtil.isNullOrBlank(obj.getNodeType())) {
						if (obj.getNodeType().indexOf((String) map2.get("entityKey")) >= 0) {
							if (!dataMapQuery.contains((Integer) map2.get("id"))) {
								dataMapQuery.add((Integer) map2.get("id"));
								dataQuery.add(map2);
								nodesQuery.add(treeNode1);
								// getParentById(dataQuery,nodesQuery, data,
								// (Integer)map2.get("parentId"), dataMapQuery);
							}
						}
					} else {
						if (!dataMapQuery.contains((Integer) map2.get("id"))) {
							dataMapQuery.add((Integer) map2.get("id"));
							dataQuery.add(map2);
							nodesQuery.add(treeNode1);
							// getParentById(dataQuery,nodesQuery, data,
							// (Integer)map2.get("parentId"), dataMapQuery);
						}
					}
				}

			}

			if (asyncTreeLoad) {
				for (TreeNode treeNode : nodes) {
					if (treeNode.getNodeId().equals(obj.getId()) && "0".equals(treeNode.getTreeLevel()) ) {
						nodes = new ArrayList<>();
						nodes.add(treeNode);
						if (!StringUtil.isNullOrBlank(obj.getNodeType())
								|| !StringUtil.isNullOrBlank(obj.getNodeName())) {
							if (!StringUtil.isNullOrBlank(obj.getNodeType())
									&& !StringUtil.isNullOrBlank(obj.getNodeName())) {
								nodesQuery = new ArrayList<>();
								dataMapQuery = new ArrayList<>();
								List<Map<String, Object>> parentData = new ArrayList<>();
								for (Map<String, Object> map3 : dataQuery) {
									getParentById(parentData, nodesQuery, dataQuery, (Integer) map3.get("parentId"),
											dataMapQuery);
									if (parentData != null && parentData.size() == 0) {
										getParentById(parentData, nodesQuery, data, (Integer) map3.get("parentId"),
												dataMapQuery);
										for (Map<String, Object> map4 : dataQuery) {
											for (Map<String, Object> map5 : parentData) {
												if (((Integer) map4.get("id"))
														.equals(((Integer) map5.get("parentId")))) {
													map3.put("parentId", (Integer) map5.get("parentId"));
												}
											}
										}
									}
									TreeNode treeNode1 = commonTree.transform(map3);
									nodesQuery2.add(treeNode1);
								}

								maps.put("treeJson", nodesQuery2);
							} else {
								nodesQuery = new ArrayList<>();
								dataMapQuery = new ArrayList<>();
								for (Map<String, Object> map3 : dataQuery) {
									List<Map<String, Object>> parentData = new ArrayList<>();
									getParentById(parentData, nodesQuery2, dataQuery, (Integer) map3.get("parentId"),
											dataMapQuery);
									if (parentData != null && parentData.size() == 0) {
										getParentById(parentData, nodesQuery2, data, (Integer) map3.get("parentId"),
												dataMapQuery);
										for (Map<String, Object> map4 : dataQuery) {
											for (Map<String, Object> map5 : parentData) {
												if (((Integer) map4.get("id"))
														.equals(((Integer) map5.get("parentId")))) {
													map3.put("parentId", (Integer) map5.get("parentId"));
												}
											}
										}
									}
									TreeNode treeNode1 = commonTree.transform(map3);
									nodesQuery.add(treeNode1);
								}
								maps.put("treeJson", nodesQuery);
							}
						} else {

							maps.put("treeJson", nodes);
						}
					}

				}
			} else {
				if (!StringUtil.isNullOrBlank(obj.getNodeType()) || !StringUtil.isNullOrBlank(obj.getNodeName())) {
					if (!StringUtil.isNullOrBlank(obj.getNodeType()) && !StringUtil.isNullOrBlank(obj.getNodeName())) {
						nodesQuery = new ArrayList<>();
						dataMapQuery = new ArrayList<>();
						List<Map<String, Object>> parentData = new ArrayList<>();
						for (Map<String, Object> map3 : dataQuery) {
							getParentById(parentData, nodesQuery, dataQuery, (Integer) map3.get("parentId"),
									dataMapQuery);
							if (parentData != null && parentData.size() == 0) {
								getParentById(parentData, nodesQuery, data, (Integer) map3.get("parentId"),
										dataMapQuery);
								for (Map<String, Object> map4 : dataQuery) {
									for (Map<String, Object> map5 : parentData) {
										if (((Integer) map4.get("id")).equals(((Integer) map5.get("parentId")))) {
											map3.put("parentId", (Integer) map5.get("parentId"));
										}
									}
								}
							}
							TreeNode treeNode1 = commonTree.transform(map3);
							nodesQuery2.add(treeNode1);
						}

						maps.put("treeJson", nodesQuery2);
					} else {
						nodesQuery = new ArrayList<>();
						dataMapQuery = new ArrayList<>();
						for (Map<String, Object> map3 : dataQuery) {
							List<Map<String, Object>> parentData = new ArrayList<>();
							getParentById(parentData, nodesQuery2, dataQuery, (Integer) map3.get("parentId"),
									dataMapQuery);
							if (parentData != null && parentData.size() == 0) {
								getParentById(parentData, nodesQuery2, data, (Integer) map3.get("parentId"),
										dataMapQuery);
								for (Map<String, Object> map4 : dataQuery) {
									for (Map<String, Object> map5 : parentData) {
										if (((Integer) map4.get("id")).equals(((Integer) map5.get("parentId")))) {
											map3.put("parentId", (Integer) map5.get("parentId"));
										}
									}
								}
							}
							TreeNode treeNode1 = commonTree.transform(map3);
							nodesQuery.add(treeNode1);
						}
						maps.put("treeJson", nodesQuery);
					}
				} else {
					maps.put("treeJson", nodes);
				}
			}
		} else {

			Map<String, Integer> map = new HashMap<>();
			// map.put("id", obj.getId());
			EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(obj.getRootEntityKey());
			// 获取实体定义
			if (null == entityInfo) {
				throw new ServiceException("crud.error.entity.definition", obj.getRootEntityKey());
			}
			List<Object> params = new ArrayList<>();
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append("select b.* from portal_tree_node_ref b ");
			// params.add(obj.getTreeTypeCode());
			// params.add(obj.getId());
			List<Map<String, Object>> data1 = jdbcDao.queryForListMap(stringBuffer.toString(), params);
			params = new ArrayList<>();
			String sql = "";

			List<Map<String, Object>> data = new ArrayList<>();
			for (JSONObject treeNodeBean2 : treeNodeBeans) {
				TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
				entityInfo = entityInfoQueryService.queryEntityInfo(treeNodeBean.getEntityKey());
				// 获取实体定义
				if (null == entityInfo) {
					throw new ServiceException("crud.error.entity.definition", obj.getRootEntityKey());
				}
				params = new ArrayList<>();
				sql = this.buildFindSql(entityInfo.getTableName(), map, entityInfo.getAttrs(), entityInfo.getExtAttrs(),
						false, params);
				List<Map<String, Object>> datas = jdbcDao.queryForListMap(sql, params);
				for (Map<String, Object> map2 : datas) {
					map2.put("treeLevel", treeNodeBean.getTreeLevel());
					map2.put("entityName", entityInfo.getEntityName());
					map2.put("entityKey", treeNodeBean.getEntityKey());

                    String parentKey = mapParentKey.get(treeNodeBean.getEntityKey())!=null && mapParentKey.get(treeNodeBean.getEntityKey()).indexOf("-")>=0 ? (mapParentKey.get(treeNodeBean.getEntityKey()).split("-")[0]+String.valueOf(map2.get("parentId")) +"-"+ mapParentKey.get(treeNodeBean.getEntityKey()).split("-")[1]+String.valueOf(map2.get("parentId")) ) :(mapParentKey.get(treeNodeBean.getEntityKey())+String.valueOf(map2.get("parentId"))) ;
                    map2.put("parentKey",treeNodeBean.getTreeLevel()!=0? parentKey:null);
                    map2.put("idKey", treeNodeBean.getEntityKey()+String.valueOf(map2.get("id")));
					for (Map<String, Object> map3 : data1) {
						if (((String) map3.get("entityId")).equals(String.valueOf(map2.get("id")))) {
							map2.put("parentId", map3.get("parentId"));
							data.add(map2);
						}
					}
				}

			}
			List<TreeNode> nodes = new ArrayList<>();
			List<String> dataMap = new ArrayList<>();
			List<TreeNode> nodesQuery = new ArrayList<>();
			List<TreeNode> nodesQuery2 = new ArrayList<>();
			List<Integer> dataMapQuery = new ArrayList<>();
			List<Map<String, Object>> dataQuery = new ArrayList<>();
			dataMap = getChildById(dataMap, data,obj.getRootEntityKey()+ obj.getId());
			for (Map<String, Object> map2 : data) {
				if (dataMap.contains((String) map2.get("entityKey")+(Integer) map2.get("id"))) {
					for (Map<String, Object> map3 : data) {
						List children = new ArrayList<>();
						if (map3.get("parentId") != null
								&& ((Integer) map3.get("parentId")).equals((Integer) map2.get("id"))) {
							children.add(map3);
						}
						map2.put("children", children);
					}
					// if(((Integer)map2.get("id")).equals(obj.getId())){
					TreeNode treeNode = commonTree.transform(map2);
					nodes.add(treeNode);
					// }
					TreeNode treeNode1 = commonTree.transform(map2);
					if (!StringUtil.isNullOrBlank(obj.getNodeName()) && !StringUtil.isNullOrBlank(obj.getNodeType())) {
						if (obj.getNodeType().indexOf((String) map2.get("entityKey")) >= 0) {
							for (JSONObject treeNodeBean2 : treeNodeBeans) {
								TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
								String displayName = treeNodeBean2.getJSONObject("display").getString("displayName");
								if (treeNodeBean.getEntityKey().equals((String) map2.get("entityKey"))) {
									if (((String) map2.get(displayName))
											.indexOf(obj.getNodeName()) >= 0) {
										if (!dataMapQuery.contains((Integer) map2.get("id"))) {
											dataMapQuery.add((Integer) map2.get("id"));
											dataQuery.add(map2);
											nodesQuery2.add(treeNode1);
											getParentById(dataQuery, nodesQuery2, data, (Integer) map2.get("parentId"),
													dataMapQuery, obj.getNodeType());
										}
									}
								}

							}
						}

					} else if (!StringUtil.isNullOrBlank(obj.getNodeName())) {
						for (JSONObject treeNodeBean2 : treeNodeBeans) {
							TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
							String displayName = treeNodeBean2.getJSONObject("display").getString("displayName");
							if (treeNodeBean.getEntityKey().equals((String) map2.get("entityKey"))) {
								if (((String) map2.get(displayName))
										.indexOf(obj.getNodeName()) >= 0) {
									if (!dataMapQuery.contains((Integer) map2.get("id"))) {
										dataMapQuery.add((Integer) map2.get("id"));
										dataQuery.add(map2);
										nodesQuery.add(treeNode1);
										getParentById(dataQuery, nodesQuery, data, (Integer) map2.get("parentId"),
												dataMapQuery);
									}
								}
							}

						}
					} else if (!StringUtil.isNullOrBlank(obj.getNodeType())) {
						if (obj.getNodeType().indexOf((String) map2.get("entityKey")) >= 0) {
							if (!dataMapQuery.contains((Integer) map2.get("id"))) {
								dataMapQuery.add((Integer) map2.get("id"));
								dataQuery.add(map2);
								nodesQuery.add(treeNode1);
								// getParentById(dataQuery,nodesQuery, data,
								// (Integer)map2.get("parentId"), dataMapQuery);
							}
						}
					} else {
                        if (!dataMapQuery.contains((Integer) map2.get("id"))) {
                            dataMapQuery.add((Integer) map2.get("id"));
                            dataQuery.add(map2);
                            nodesQuery.add(treeNode1);
                            // getParentById(dataQuery,nodesQuery, data,
                            // (Integer)map2.get("parentId"), dataMapQuery);
                        }
                    }

				}
			}
			if (asyncTreeLoad) {
				for (TreeNode treeNode : nodes) {
					if (treeNode.getNodeId().equals(obj.getId())) {
						nodes = new ArrayList<>();
						nodes.add(treeNode);
						if (!StringUtil.isNullOrBlank(obj.getNodeType())
								|| !StringUtil.isNullOrBlank(obj.getNodeName())) {
							if (!StringUtil.isNullOrBlank(obj.getNodeType())
									&& !StringUtil.isNullOrBlank(obj.getNodeName())) {
								nodesQuery = new ArrayList<>();
								for (Map<String, Object> map3 : dataQuery) {
									List<Map<String, Object>> parentData = new ArrayList<>();
									dataMapQuery = new ArrayList<>();
									getParentById(parentData, nodesQuery, dataQuery, (Integer) map3.get("parentId"),
											dataMapQuery);
									if (parentData != null && parentData.size() == 0) {
										getParentById(parentData, nodesQuery, data, (Integer) map3.get("parentId"),
												dataMapQuery);
										for (Map<String, Object> map4 : dataQuery) {
											for (Map<String, Object> map5 : parentData) {
												if (((Integer) map4.get("id"))
														.equals(((Integer) map5.get("parentId")))) {
													map3.put("parentId", (Integer) map5.get("parentId"));
												}
											}
										}
									}
									TreeNode treeNode1 = commonTree.transform(map3);
									nodesQuery2.add(treeNode1);
								}

								maps.put("treeJson", nodesQuery2);
							} else {
								nodesQuery = new ArrayList<>();
								for (Map<String, Object> map3 : dataQuery) {
									List<Map<String, Object>> parentData = new ArrayList<>();
									dataMapQuery = new ArrayList<>();
									getParentById(parentData, nodesQuery2, dataQuery, (Integer) map3.get("parentId"),
											dataMapQuery);
									if (parentData != null && parentData.size() == 0) {
										getParentById(parentData, nodesQuery2, data, (Integer) map3.get("parentId"),
												dataMapQuery);
										for (Map<String, Object> map4 : dataQuery) {
											for (Map<String, Object> map5 : parentData) {
												if (((Integer) map4.get("id"))
														.equals(((Integer) map5.get("parentId")))) {
													map3.put("parentId", (Integer) map5.get("parentId"));
												}
											}
										}
									}
									TreeNode treeNode1 = commonTree.transform(map3);
									nodesQuery.add(treeNode1);
								}
								maps.put("treeJson", nodesQuery);
							}
						} else {
							maps.put("treeJson", nodes);
						}
					}
				}
			} else {
				maps.put("treeJson", nodes);
			}
		}
		return maps;
	}

	public List<String> getChildById(List<String> dataMap, List<Map<String, Object>> data, String idKey) {
		for (Map<String, Object> map2 : data) {
			if (map2.get("idKey") != null && ((String) map2.get("idKey")).equals(idKey)) {
				if (!dataMap.contains((String) map2.get("idKey"))) {
					dataMap.add((String) map2.get("entityKey")+(Integer) map2.get("id"));
				}
			}
			if (map2.get("parentKey") != null && ((String)map2.get("parentKey")).indexOf(idKey)>=0) {
				if (!dataMap.contains((String) map2.get("entityKey")+(Integer) map2.get("id"))) {
					dataMap.add((String) map2.get("entityKey")+(Integer) map2.get("id"));
					getChildById(dataMap, data, (String)map2.get("idKey"));
				}
			}
		}
		return dataMap;
	}


	// 查找节点的子节点
//	public List getChildRenById(List dataMap, List<Map<String, Object>> data, Integer id) {
//		for (Map<String, Object> map2 : data) {
//			if (map2.get("id") != null && ((Integer) map2.get("id")).equals(id)) {
//				if (!dataMap.contains((Integer) map2.get("id"))) {
//					dataMap.add(map2);
//				}
//			}
//			if (map2.get("parentId") != null && ((Integer) map2.get("parentId")).equals(id)) {
//				if (!dataMap.contains((Integer) map2.get("id"))) {
//					dataMap.add(map2);
//				}
//				getChildById(dataMap, data, (Integer) map2.get("id"));
//			}
//		}
//		return dataMap;
//	}

	// 查找节点的父节点
	public List<Map<String, Object>> getParentById(List<Map<String, Object>> dataMap, List<TreeNode> nodes,
			List<Map<String, Object>> data, Integer id, List<Integer> ids) {
		for (Map<String, Object> map2 : data) {
			CommonTree commonTree = new CommonTree();
			if (map2.get("id") != null && ((Integer) map2.get("id")).equals(id)) {
				if (!ids.contains((Integer) map2.get("id"))) {
					ids.add((Integer) map2.get("id"));
					TreeNode treeNode = commonTree.transform(map2);
					nodes.add(treeNode);
					dataMap.add(map2);
					getParentById(dataMap, nodes, data, (Integer) map2.get("parentId"), ids);
				}
			}
		}
		return dataMap;
	}

	public List<Map<String, Object>> getParentById(List<Map<String, Object>> dataMap, List<TreeNode> nodes,
			List<Map<String, Object>> data, Integer id, List<Integer> ids, String nodeType) {
		for (Map<String, Object> map2 : data) {
			CommonTree commonTree = new CommonTree();
			if (map2.get("id") != null && ((Integer) map2.get("id")).equals(id)) {
				if (!ids.contains((Integer) map2.get("id")) && nodeType.indexOf((String) map2.get("entityKey")) >= 0) {
					ids.add((Integer) map2.get("id"));
					// TreeNode treeNode = commonTree.transform(map2);
					// nodes.add(treeNode);
					dataMap.add(map2);
					getParentById(dataMap, nodes, data, (Integer) map2.get("parentId"), ids, nodeType);
				}
			}
		}
		return dataMap;
	}

	@Override
	public void moveTree(PortalTreeMoveBean obj) {
		if ("top".equals(obj.getDropType())) {
			obj.setVal(1);
			updateOrder(obj);
		} else if ("bottom".equals(obj.getDropType())) {
			obj.setVal(-1);
			updateOrder(obj);
		} else if ("append".equals(obj.getDropType())) {
			obj.setVal(1);
			updateOrder(obj);
		}
	}

	public void updateOrder(PortalTreeMoveBean obj) {
		try {
			EntityInfoBean startEntityInfo = entityInfoQueryService.queryEntityInfo(obj.getEntityKey());
			EntityInfoBean endEntityInfo = entityInfoQueryService.queryEntityInfo(obj.getTargetEntityKey());
			List<Object> params = new ArrayList<>();
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append("select a.* from " + endEntityInfo.getTableName() + " a  where a.id =? ");
			params.add(obj.getTargetId());
			List<Map<String, Object>> enddata1 = jdbcDao.queryForListMap(stringBuffer.toString(), params);
			params = new ArrayList<>();
			stringBuffer = new StringBuffer();
			stringBuffer.append("select a.* from " + startEntityInfo.getTableName() + " a  where a.id =? ");
			params.add(obj.getId());
			List<Map<String, Object>> startdata1 = jdbcDao.queryForListMap(stringBuffer.toString(), params);
			// 根据拖动查询起始的实体
			String sql = "";
			List<Object> param = null;
			if (obj.getStoreType() == 2) {
				sql = "update portal_tree_node_ref set parentId =? where id = ? ";
				param = new ArrayList<>();
				param.add((Integer) enddata1.get(0).get("parentId"));
				param.add(obj.getId());
				jdbcDao.executeBySQL(sql, param);
			}
			if ("append".equals(obj.getDropType())) {
				if (obj.getStoreType() == 1) {
					stringBuffer = new StringBuffer();
					params = new ArrayList<>();
					stringBuffer.append("select max(displaySequence) as displaySequence  from "
							+ endEntityInfo.getTableName() + " where parentId = ? ");
					params.add((Integer) enddata1.get(0).get("parentId"));
					List<Map<String, Object>> max = jdbcDao.queryForListMap(stringBuffer.toString(), params);

					sql = "update " + startEntityInfo.getTableName()
							+ " set parentId = ? , displaySequence =?   where id=?";
					param = new ArrayList<>();
					param.add((Integer) enddata1.get(0).get("id"));
					param.add((Integer) max.get(0).get("displaySequence"));
					param.add(obj.getId());
					jdbcDao.executeBySQL(sql, param);
				} else {

					stringBuffer = new StringBuffer();
					params = new ArrayList<>();
					stringBuffer.append("select max(displaySequence) as displaySequence  from "
							+ endEntityInfo.getTableName() + " where parentId = ? ");
					params.add((Integer) enddata1.get(0).get("parentId"));
					List<Map<String, Object>> max = jdbcDao.queryForListMap(stringBuffer.toString(), params);

					sql = "update " + startEntityInfo.getTableName() + " set  displaySequence =?    where id=?";
					param = new ArrayList<>();
					param.add((Integer) max.get(0).get("displaySequence"));
					param.add(obj.getId());
					jdbcDao.executeBySQL(sql, param);
				}
			} else {
				// 暂时屏蔽
				if (endEntityInfo != null) {
					// 判断大小
					List<Map<String, Object>> list = null;
					if (((Integer) enddata1.get(0).get("parentId"))
							.equals((Integer) startdata1.get(0).get("parentId"))) {

						if ((Integer) startdata1.get(0).get("displaySequence") > (Integer) enddata1.get(0)
								.get("displaySequence")) {
							params = new ArrayList<>();
							stringBuffer = new StringBuffer();
							stringBuffer.append("select a.* from " + startEntityInfo.getTableName()
									+ " a  where a.displaySequence >=? and a.displaySequence<=? ");
							params.add((Integer) enddata1.get(0).get("displaySequence"));
							params.add((Integer) startdata1.get(0).get("displaySequence"));
							list = jdbcDao.queryForListMap(stringBuffer.toString(), params);
							// list =
							// sysMenuDao.getZhongJian((Integer)enddata1.get(0).get("displaySequence"),
							// (Integer)startdata1.get(0).get("displaySequence"));
						} else {
							params = new ArrayList<>();
							stringBuffer = new StringBuffer();
							stringBuffer.append("select a.* from " + startEntityInfo.getTableName()
									+ " a  where a.displaySequence >=? and a.displaySequence<=? ");
							params.add((Integer) startdata1.get(0).get("displaySequence"));
							params.add((Integer) enddata1.get(0).get("displaySequence"));
							list = jdbcDao.queryForListMap(stringBuffer.toString(), params);
						}
					} else {
						if ("bottom".equals(obj.getDropType())) {
							params = new ArrayList<>();
							stringBuffer = new StringBuffer();
							stringBuffer.append("select a.* from " + endEntityInfo.getTableName()
									+ " a  where a.displaySequence <=? ");
							params.add((Integer) enddata1.get(0).get("displaySequence"));
							list = jdbcDao.queryForListMap(stringBuffer.toString(), params);
							// list =
							// sysMenuDao.getZhongJian((Integer)enddata1.get(0).get("displaySequence"),
							// (Integer)startdata1.get(0).get("displaySequence"));
						} else {
							params = new ArrayList<>();
							stringBuffer = new StringBuffer();
							stringBuffer.append("select a.* from " + endEntityInfo.getTableName()
									+ " a  where a.displaySequence >=?  ");
							params.add((Integer) enddata1.get(0).get("displaySequence"));
							list = jdbcDao.queryForListMap(stringBuffer.toString(), params);
						}
					}
					// System.out.println("先更新的："+endOrder.getDispOrder());
					// 循环设置顺序
					for (Map<String, Object> map : list) {
						sql = "update " + endEntityInfo.getTableName() + " set displaySequence =?   where id=?";
						param = new ArrayList<>();
						param.add(((Integer) map.get("displaySequence")) + obj.getVal());
						param.add(map.get("id"));
						jdbcDao.executeBySQL(sql, param);
					}
					// 交换拖拽之间的顺序
					sql = "update " + startEntityInfo.getTableName()
							+ " set parentId = ? , displaySequence =?   where id=?";
					param = new ArrayList<>();
					param.add((Integer) enddata1.get(0).get("parentId"));
					param.add((Integer) enddata1.get(0).get("displaySequence"));
					param.add(obj.getId());
					jdbcDao.executeBySQL(sql, param);

				}
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public Map<String, Object> queryTreeByCodeAndChildEntityKeyAndLevel(PortalTreeBean obj) {
		// TODO Auto-generated method stub
		return null;
	}

	public String buildFindSql(String tableName, Map<String, Integer> map, List<EntityFieldInfoBean> fieldInfoBeans,
                               List<EntityFieldInfoBean> extfieldInfoBeans, boolean camelCase, List<Object> params) {

		StringBuilder sqlBuilder = new StringBuilder("select ");
		// String findWhereSql = " where ";
		int i = 0;
		for (EntityFieldInfoBean info : fieldInfoBeans) {
			EntityFieldDetailBean detail = info.getField();
			String columnName = StringUtil.isNullOrBlank(detail.getPhysicalField()) ? detail.getFieldName()
					: detail.getPhysicalField();
			String fieldName = StringUtil.isNullOrBlank(detail.getFieldName()) ? detail.getPhysicalField()
					: detail.getFieldName();
			// 处理驼峰,以别名的方式适应前端取字段
			if (camelCase) {
				// columnName = nameHandler.getColumnName(detail.getFieldName(),
				// camelCase);
			}
			if(info.getField().getIsPk()==1){
				if (info.getField().getFieldType() != 6) {
					sqlBuilder.append(" " + columnName).append(" as id");
					if (i != fieldInfoBeans.size() - 1) {
						sqlBuilder.append(",");
					}
				}
			}else{
				if (info.getField().getFieldType() != 6) {
					sqlBuilder.append(" " + columnName).append(" as " + fieldName);
					if (i != fieldInfoBeans.size() - 1) {
						sqlBuilder.append(",");
					}
				}
			}

			i++;
		}
		if (extfieldInfoBeans != null && extfieldInfoBeans.size() > 0) {
			sqlBuilder.append(",extAttrs");
		}
		sqlBuilder.append(" from ").append(tableName);
		// 去掉最后一个，
		String sql = sqlBuilder.toString();
		// sql += findWhereSql;
		// doValidation(sql);
		return sql;
	}

	@Override
	public Integer addNode(String entityName, Map<String, Object> param, AttachmentFormBean attachments) {
		// TODO Auto-generated method stub
		// 获取实体定义
		EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(entityName);
		// 获取实体定义
		if (null == entityInfo) {
			throw new ServiceException("crud.error.entity.definition", entityName);
		}
		Integer id = null;
		if ((Integer) param.get("storeType") == 1) {
			List<Object> params = new ArrayList<>();
			String sql = crudSqlGenerateUtils.buildInsertSql(entityInfo.getTableName(), param, entityInfo.getAttrs(),
					entityInfo.getExtAttrs(), false, params);
			id = jdbcDao.insertBySQLAndGetKey(sql, params);
			if (param.get("generateFormId") != null) {
				portalAttachmentService.saveAttachmentForm(param.get("generateFormId").toString(),
						attachments != null ? attachments.getAttachments() : null);
			}
		} else {
			List<Object> params = new ArrayList<>();
			String sql = crudSqlGenerateUtils.buildInsertSql(entityInfo.getTableName(), param, entityInfo.getAttrs(),
					entityInfo.getExtAttrs(), false, params);
			id = jdbcDao.insertBySQLAndGetKey(sql, params);
			if (param.get("generateFormId") != null) {
				portalAttachmentService.saveAttachmentForm(param.get("generateFormId").toString(),
						attachments != null ? attachments.getAttachments() : null);
			}
			if (param.get("id") == null) {
				PortalTree portalTree = new PortalTree();
				portalTree.setTreeCode("");
				portalTree.setTreeName("");
				portalTree.setTreeTypeCode("");
				portalTree.setEntityId(id);
				portalTree.setCreateUser(SpringWebUtils.getRequestUser());
				portalTree.setCreateTime(new Date());
				portalTree.setLastUpdateTime(new Date());
				portalTree.setLastUpdateUser(SpringWebUtils.getRequestUser());
				portalTree.setCompanyCode(SpringWebUtils.getRequestCompany());
				portalTree.setOptCounter(0);
				portalTreeService.insert(portalTree);
				PortalTreeNodeRef portalTreeNodeRef = new PortalTreeNodeRef();
				portalTreeNodeRef.setTreeId(portalTree.getId());
				portalTreeNodeRef.setParentId(param.get("parentId") != null ? (Integer) param.get("parentId") : null);
				portalTreeNodeRef.setEntityId(id);
				portalTreeNodeRef.setCreateUser(SpringWebUtils.getRequestUser());
				portalTreeNodeRef.setCreateTime(new Date());
				portalTreeNodeRef.setLastUpdateTime(new Date());
				portalTreeNodeRef.setLastUpdateUser(SpringWebUtils.getRequestUser());
				portalTreeNodeRef.setCompanyCode(SpringWebUtils.getRequestCompany());
				portalTreeNodeRef.setOptCounter(0);
				portalTreeNodeRefService.insert(portalTreeNodeRef);
			} else {
				// StringBuffer stringBuffer = new StringBuffer() ;
				// stringBuffer.append("select a.* from portal_tree_ref a where
				// a.treeTypeCode=? and a.entityId = ? " );
				// params.add(param.get("treeTypeCode"));
				// params.add(param.get("id"));
				// List<Map<String, Object>> data1 =
				// jdbcDao.queryForListMap(stringBuffer.toString(),params);
				PortalTreeNodeRef portalTree = new PortalTreeNodeRef();
				portalTree.setTreeId(0);
				portalTree.setParentId((Integer) param.get("parentId"));
				portalTree.setEntityId(id);
				portalTree.setCreateUser(SpringWebUtils.getRequestUser());
				portalTree.setCreateTime(new Date());
				portalTree.setLastUpdateTime(new Date());
				portalTree.setLastUpdateUser(SpringWebUtils.getRequestUser());
				portalTree.setCompanyCode(SpringWebUtils.getRequestCompany());
				portalTree.setOptCounter(0);
				portalTreeNodeRefService.insert(portalTree);
			}
		}
		return id;
	}

	@Override
	public void deleteNode(String entityName, Map<String, Object> param) {
		// 获取实体定义
		EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(entityName);
		// 获取实体定义
		if (null == entityInfo) {
			throw new ServiceException("crud.error.entity.definition", entityName);
		}
		List<Object> params = new ArrayList<>();
		String sql = crudSqlGenerateUtils.buildDeleteSql(entityInfo.getTableName(), param, entityInfo.getAttrs(),
				params);
		jdbcDao.executeBySQL(sql, params);
	}

	@Override
	public Map<String, Object> queryTreeByCodeAndRootEntityKeyAjax(PortalTreeBean obj) {
		// TODO Auto-generated method stub
		CommonTree commonTree = new CommonTree();
		Map<String, Object> maps = new HashMap<>();
		PortalTreeType portalTreeType = portalTreeTypeService.selectByTreeByCodeAndRootEntityKey(obj.getTreeTypeCode(),
				obj.getRootEntityKey());
		// maps.put("treeStructure", portalTreeType.getTreeStructure());
		Map<String, String> mapParentKey = new HashMap<>();
		List<JSONObject> treeNodeBeans = (List<JSONObject>) JSONObject
				.parseObject(portalTreeType.getTreeStructure()).get("Nodes");
		for (JSONObject treeNodeBean2 : treeNodeBeans) {
			TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
			// if(treeNodeBean.getTreeLevel()== (num+1)){
			//if (obj.getEntityKey().equals(treeNodeBean.getEntityKey()) ) {
				JSONArray jsonArrays = treeNodeBean2.getJSONArray("childs");
				if (jsonArrays.size() > 0) {
					for (int i = 0; i < jsonArrays.size(); i++) {
						JSONObject job = jsonArrays.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
						String entityKey = job.getString("entityKey");
						if(mapParentKey.containsKey(entityKey)){
                            mapParentKey.put(entityKey,mapParentKey.get(entityKey)+"-"+treeNodeBean.getEntityKey());
                        }else{
                            mapParentKey.put(entityKey,treeNodeBean.getEntityKey());
                        }


					}
				}
			//}
		}
		if (portalTreeType.getStoreType() == 1) {
			Map<String, Integer> map = new HashMap<>();
			EntityInfoBean entityInfo = null;
			List<Object> params = new ArrayList<>();
			String sql = "";
			List<Map<String, Object>> datas = new ArrayList<>();
			List<Map<String, Object>> data = new ArrayList<>();
//			data.addAll(datas);
			// int num = 0 ;
			// for (JSONObject treeNodeBean2 : treeNodeBeans) {
			// TreeNodeBean treeNodeBean =
			// JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
			// if(treeNodeBean.getEntityKey().equals(obj.getEntityKey())){
			// num = treeNodeBean.getTreeLevel() ;
			// }
			// }
			for (JSONObject treeNodeBean2 : treeNodeBeans) {
				TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
				// if(treeNodeBean.getTreeLevel()== (num+1)){
				if (obj.getEntityKey().equals(treeNodeBean.getEntityKey()) ) {
					JSONArray jsonArrays = treeNodeBean2.getJSONArray("childs") ;
					if(jsonArrays.size()>0){
						for(int i=0;i<jsonArrays.size();i++){
							JSONObject job = jsonArrays.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
							String entityKey = job.getString("entityKey") ;
							if(StringUtils.isNotBlank(entityKey)){
								entityInfo = entityInfoQueryService.queryEntityInfo(entityKey);
								// 获取实体定义
								if (null == entityInfo) {
									throw new ServiceException("crud.error.entity.definition", obj.getRootEntityKey());
								}
								params = new ArrayList<>();
								sql = this.buildFindSql(entityInfo.getTableName(), map, entityInfo.getAttrs(), entityInfo.getExtAttrs(),
										false, params);
								sql += " where parent_id = ? " ;
								params.add(obj.getId());
								datas = jdbcDao.queryForListMap(sql, params);
								List<Map<String, Object>> datas1 = new ArrayList<>();
								for (Map<String, Object> map2 : datas) {
									// if(map2.get("parentId")!=null){
									map2.put("entityKey", entityKey);
									map2.put("treeLevel", job.getInteger("treeLevel"));
									map2.put("entityName", entityInfo.getEntityName());
									String parentKey =mapParentKey.get(entityKey)!=null && mapParentKey.get(entityKey).indexOf("-")>=0 ? (mapParentKey.get(entityKey).split("-")[0]+String.valueOf(map2.get("parentId")) +"-"+ mapParentKey.get(entityKey).split("-")[1]+String.valueOf(map2.get("parentId")) ) :(mapParentKey.get(entityKey)+String.valueOf(map2.get("parentId"))) ;
									map2.put("parentKey",job.getInteger("treeLevel")!=0? parentKey:null);
									map2.put("idKey", entityKey+String.valueOf(map2.get("id")));
									datas1.add(map2);
									// }
								}
								data.addAll(datas1);
							}
							// System.out.println(job.get("entityKey")+"=") ;  // 得到 每个对象中的属性值
						}
					}else {
						entityInfo = entityInfoQueryService.queryEntityInfo(obj.getEntityKey());
						// 获取实体定义
						if (null == entityInfo) {
							throw new ServiceException("crud.error.entity.definition", obj.getRootEntityKey());
						}
						params = new ArrayList<>();
						sql = this.buildFindSql(entityInfo.getTableName(), map, entityInfo.getAttrs(), entityInfo.getExtAttrs(),
								false, params);
						sql += " where parent_id = ? " ;
						params.add(obj.getId());
						datas = jdbcDao.queryForListMap(sql, params);
						List<Map<String, Object>> datas1 = new ArrayList<>();
						for (Map<String, Object> map2 : datas) {
							// if(map2.get("parentId")!=null){
							map2.put("entityKey", treeNodeBean.getEntityKey());
							map2.put("treeLevel", treeNodeBean.getTreeLevel());
							map2.put("entityName", entityInfo.getEntityName());
                            String parentKey = mapParentKey.get(treeNodeBean.getEntityKey())!=null && mapParentKey.get(treeNodeBean.getEntityKey()).indexOf("-")>=0 ? (mapParentKey.get(treeNodeBean.getEntityKey()).split("-")[0]+String.valueOf(map2.get("parentId")) +"-"+ mapParentKey.get(treeNodeBean.getEntityKey()).split("-")[1]+String.valueOf(map2.get("parentId")) ) :(mapParentKey.get(treeNodeBean.getEntityKey())+String.valueOf(map2.get("parentId"))) ;
                            map2.put("parentKey",treeNodeBean.getTreeLevel()!=0? parentKey:null);
							map2.put("idKey", treeNodeBean.getEntityKey()+String.valueOf(map2.get("id")));
							datas1.add(map2);
							// }
						}
						data.addAll(datas1);
					}
				}

				// }
			}
			List<TreeNode> nodes = new ArrayList<>();
			List<String> dataMap = new ArrayList<>();
			List<TreeNode> nodesQuery = new ArrayList<>();
			List<Integer> dataMapQuery = new ArrayList<>();
			List<TreeNode> nodesQuery2 = new ArrayList<>();
			List<Map<String, Object>> dataQuery = new ArrayList<>();
			dataMap = getChildById(dataMap, data, obj.getEntityKey()+obj.getId());
			for (Map<String, Object> map2 : data) {
				if (dataMap.contains((String) map2.get("entityKey")+(Integer) map2.get("id"))) {
					if (map2.get("parentId") != null
							&& ((Integer) map2.get("parentId")).equals((Integer) obj.getId())) {
						TreeNode treeNode = commonTree.transform(map2);
						nodes.add(treeNode);
					}
					TreeNode treeNode1 = commonTree.transform(map2);
					if (!StringUtil.isNullOrBlank(obj.getNodeName()) && !StringUtil.isNullOrBlank(obj.getNodeType())) {
						if (obj.getNodeType().indexOf((String) map2.get("entityKey")) >= 0) {
							for (JSONObject treeNodeBean2 : treeNodeBeans) {
								TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
								String displayName = treeNodeBean2.getJSONObject("display").getString("displayName");
								if (treeNodeBean.getEntityKey().equals((String) map2.get("entityKey"))) {
									if (((String) map2.get(displayName))
											.indexOf(obj.getNodeName()) >= 0) {
										if (!dataMapQuery.contains((Integer) map2.get("id"))) {
											dataMapQuery.add((Integer) map2.get("id"));
											dataQuery.add(map2);
											// nodesQuery2.add(treeNode1);
											getParentById(dataQuery, nodesQuery2, data, (Integer) map2.get("parentId"),
													dataMapQuery, obj.getNodeType());
										}
									}
								}

							}
						}

					} else if (!StringUtil.isNullOrBlank(obj.getNodeName())) {
						for (JSONObject treeNodeBean2 : treeNodeBeans) {
							TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
							String displayName = treeNodeBean2.getJSONObject("display").getString("displayName");
							if (treeNodeBean.getEntityKey().equals((String) map2.get("entityKey"))) {
								if (((String) map2.get(displayName))
										.indexOf(obj.getNodeName()) >= 0) {
									if (!dataMapQuery.contains((Integer) map2.get("id"))) {
										dataMapQuery.add((Integer) map2.get("id"));
										dataQuery.add(map2);
										nodesQuery.add(treeNode1);
										getParentById(dataQuery, nodesQuery, data, (Integer) map2.get("parentId"),
												dataMapQuery);
									}
								}
							}

						}
					} else if (!StringUtil.isNullOrBlank(obj.getNodeType())) {
						if (obj.getNodeType().indexOf((String) map2.get("entityKey")) >= 0) {
							if (!dataMapQuery.contains((Integer) map2.get("id"))) {
								dataMapQuery.add((Integer) map2.get("id"));
								dataQuery.add(map2);
								nodesQuery.add(treeNode1);
								// getParentById(dataQuery,nodesQuery, data,
								// (Integer)map2.get("parentId"), dataMapQuery);
							}
						}
					}
				}
			}
			// for (TreeNode treeNode : nodes) {
			// if(treeNode.getNodeId().equals(String.valueOf(obj.getId()))){
			if (!StringUtil.isNullOrBlank(obj.getNodeType()) || !StringUtil.isNullOrBlank(obj.getNodeName())) {
				nodesQuery = new ArrayList<>();
				dataMapQuery = new ArrayList<>();
				for (Map<String, Object> map3 : dataQuery) {
					List<Map<String, Object>> parentData = new ArrayList<>();
					dataMapQuery = new ArrayList<>();
					getParentById(parentData, nodesQuery2, dataQuery, (Integer) map3.get("parentId"), dataMapQuery);
					if (parentData != null && parentData.size() == 0) {
						getParentById(parentData, nodesQuery2, data, (Integer) map3.get("parentId"), dataMapQuery);
						for (Map<String, Object> map4 : dataQuery) {
							for (Map<String, Object> map5 : parentData) {
								if (((Integer) map4.get("id")).equals(((Integer) map5.get("parentId")))) {
									map3.put("parentId", (Integer) map5.get("parentId"));
								}
							}
						}
					}
					TreeNode treeNode = commonTree.transform(map3);
					nodesQuery.add(treeNode);
				}
				maps.put("treeJson", nodesQuery);
			} else {
				maps.put("treeJson", nodes);
			}
			// }
			// }
		} else {
			Map<String, Integer> map = new HashMap<>();
			map.put("id", obj.getId());
			EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(obj.getRootEntityKey());
			// 获取实体定义
			if (null == entityInfo) {
				throw new ServiceException("crud.error.entity.definition", obj.getRootEntityKey());
			}
			List<Object> params = new ArrayList<>();
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append("select b.* portal_tree_node_ref b ");
			params.add(obj.getTreeTypeCode());
			params.add(obj.getId());
			List<Map<String, Object>> data1 = jdbcDao.queryForListMap(stringBuffer.toString(), params);
			params = new ArrayList<>();
			String sql = "";

			List<Map<String, Object>> data = new ArrayList<>();
			for (JSONObject treeNodeBean2 : treeNodeBeans) {
				TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
				entityInfo = entityInfoQueryService.queryEntityInfo(treeNodeBean.getEntityKey());
				// 获取实体定义
				if (null == entityInfo) {
					throw new ServiceException("crud.error.entity.definition", obj.getRootEntityKey());
				}
				params = new ArrayList<>();
				sql = this.buildFindSql(entityInfo.getTableName(), map, entityInfo.getAttrs(), entityInfo.getExtAttrs(),
						false, params);
				List<Map<String, Object>> datas = jdbcDao.queryForListMap(sql, params);
				for (Map<String, Object> map2 : datas) {
					map2.put("treeLevel", treeNodeBean.getTreeLevel());
					map2.put("entityName", entityInfo.getEntityName());
					map2.put("entityKey", treeNodeBean.getEntityKey());
                    String parentKey = mapParentKey.get(treeNodeBean.getEntityKey())!=null && mapParentKey.get(treeNodeBean.getEntityKey()).indexOf("-")>=0 ? (mapParentKey.get(treeNodeBean.getEntityKey()).split("-")[0]+String.valueOf(map2.get("parentId")) +"-"+ mapParentKey.get(treeNodeBean.getEntityKey()).split("-")[1]+String.valueOf(map2.get("parentId")) ) :(mapParentKey.get(treeNodeBean.getEntityKey())+String.valueOf(map2.get("parentId"))) ;
                    map2.put("parentKey",treeNodeBean.getTreeLevel()!=0? parentKey:null);
					map2.put("idKey", treeNodeBean.getEntityKey()+String.valueOf(map2.get("id")));
					for (Map<String, Object> map3 : data1) {
						if (((String) map3.get("entityId")).equals(String.valueOf(map2.get("id")))) {
							map2.put("parentId", map3.get("parentId"));
							data.add(map2);
						}
					}
				}

			}
			List<TreeNode> nodes = new ArrayList<>();
			List<String> dataMap = new ArrayList<>();
			List<TreeNode> nodesQuery = new ArrayList<>();
			List<Integer> dataMapQuery = new ArrayList<>();
			List<TreeNode> nodesQuery2 = new ArrayList<>();
			List<Map<String, Object>> dataQuery = new ArrayList<>();
			dataMap = getChildById(dataMap, data,obj.getRootEntityKey()+ obj.getId());
			for (Map<String, Object> map2 : data) {
				if (dataMap.contains((String) map2.get("entityKey")+(Integer) map2.get("id"))) {
					if (map2.get("parentId") != null
							&& ((Integer) map2.get("parentId")).equals((Integer) obj.getId())) {
						TreeNode treeNode = commonTree.transform(map2);
						nodes.add(treeNode);
					}
					TreeNode treeNode1 = commonTree.transform(map2);
					if (!StringUtil.isNullOrBlank(obj.getNodeName()) && !StringUtil.isNullOrBlank(obj.getNodeType())) {
						if (obj.getNodeType().indexOf((String) map2.get("entityKey")) >= 0) {
							for (JSONObject treeNodeBean2 : treeNodeBeans) {
								TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
								String displayName = treeNodeBean2.getJSONObject("display").getString("displayName");
								if (treeNodeBean.getEntityKey().equals((String) map2.get("entityKey"))) {
									if (((String) map2.get(displayName))
											.indexOf(obj.getNodeName()) >= 0) {
										if (!dataMapQuery.contains((Integer) map2.get("id"))) {
											dataMapQuery.add((Integer) map2.get("id"));
											dataQuery.add(map2);
											// nodesQuery2.add(treeNode1);
											getParentById(dataQuery, nodesQuery2, data, (Integer) map2.get("parentId"),
													dataMapQuery, obj.getNodeType());
										}
									}
								}

							}
						}

					} else if (!StringUtil.isNullOrBlank(obj.getNodeName())) {
						for (JSONObject treeNodeBean2 : treeNodeBeans) {
							TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
							String displayName = treeNodeBean2.getJSONObject("display").getString("displayName");
							if (treeNodeBean.getEntityKey().equals((String) map2.get("entityKey"))) {
								if (((String) map2.get(displayName))
										.indexOf(obj.getNodeName()) >= 0) {
									if (!dataMapQuery.contains((Integer) map2.get("id"))) {
										dataMapQuery.add((Integer) map2.get("id"));
										dataQuery.add(map2);
										nodesQuery.add(treeNode1);
										getParentById(dataQuery, nodesQuery, data, (Integer) map2.get("parentId"),
												dataMapQuery);
									}
								}
							}

						}
					} else if (!StringUtil.isNullOrBlank(obj.getNodeType())) {
						if (obj.getNodeType().indexOf((String) map2.get("entityKey")) >= 0) {
							if (!dataMapQuery.contains((Integer) map2.get("id"))) {
								dataMapQuery.add((Integer) map2.get("id"));
								dataQuery.add(map2);
								nodesQuery.add(treeNode1);
								// getParentById(dataQuery,nodesQuery, data,
								// (Integer)map2.get("parentId"), dataMapQuery);
							}
						}
					}
				}
			}
			if (!StringUtil.isNullOrBlank(obj.getNodeType()) || !StringUtil.isNullOrBlank(obj.getNodeName())) {
				nodesQuery = new ArrayList<>();
				dataMapQuery = new ArrayList<>();
				for (Map<String, Object> map3 : dataQuery) {
					List<Map<String, Object>> parentData = new ArrayList<>();
					getParentById(parentData, nodesQuery2, dataQuery, (Integer) map3.get("parentId"), dataMapQuery);
					if (parentData != null && parentData.size() == 0) {
						getParentById(parentData, nodesQuery2, data, (Integer) map3.get("parentId"), dataMapQuery);
						for (Map<String, Object> map4 : dataQuery) {
							for (Map<String, Object> map5 : parentData) {
								if (((Integer) map4.get("id")).equals(((Integer) map5.get("parentId")))) {
									map3.put("parentId", (Integer) map5.get("parentId"));
								}
							}
						}
					}
					TreeNode treeNode = commonTree.transform(map3);
					nodesQuery.add(treeNode);
				}
				maps.put("treeJson", nodesQuery);
			} else {
				maps.put("treeJson", nodes);
			}
		}
		return maps;
	}

	@Override
	public Map<String, Object> getTreeNodeType(PortalTreeBean obj) {
		Map<String, Object> maps = new HashMap<>();
		List<TreeNodeBean> object = new ArrayList<>();
		PortalTreeType portalTreeType = portalTreeTypeService.selectByTreeByCodeAndRootEntityKey(obj.getTreeTypeCode(),
				obj.getRootEntityKey());
		List<JSONObject> treeNodeBeans = (List<JSONObject>) JSONObject.parseObject(portalTreeType.getTreeStructure())
				.get("Nodes");
		for (JSONObject treeNodeBean2 : treeNodeBeans) {
			TreeNodeBean treeNodeBean = JSONObject.toJavaObject(treeNodeBean2, TreeNodeBean.class);
			object.add(treeNodeBean);
		}
		maps.put("treeNodeType", object);
		return maps;
	}

	@Override
	public void updateNode(String entityName, Map<String, Object> param, AttachmentFormBean attachments) {
		// 获取实体定义
		EntityInfoBean entityInfo = entityInfoQueryService.queryEntityInfo(entityName);
		// 获取实体定义
		if (null == entityInfo) {
			throw new ServiceException("crud.error.entity.definition", entityName);
		}
		List<Object> params = new ArrayList<>();
		String sql = crudSqlGenerateUtils.buildUpdateSql(entityInfo.getTableName(), param, entityInfo.getAttrs(),
				entityInfo.getExtAttrs(), false, params);
		jdbcDao.executeBySQL(sql, params);
		if (param.get("generateFormId") != null) {
			portalAttachmentService.saveAttachmentForm(param.get("generateFormId").toString(),
					attachments != null ? attachments.getAttachments() : null);
		}
	}

}
